package com.why.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.why.servicebase.exception.GuilException;
import com.why.serviceedu.service.EduSubjectService;
import com.why.serviceedu.bean.EduSubject;
import com.why.serviceedu.bean.excel.subjectData;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: guli_parent
 * @description:
 * @author: @why
 * @create: 2021-01-31 14:21
 **/
@Slf4j
public class ExcelListener extends AnalysisEventListener<subjectData> {

    //这里需要service，但是我们若不将监听器放入容器，就无法得到service
    //因此我们再controller层调用方法的时候就将得到的service传递过来
    private EduSubjectService service;
    public ExcelListener(){}
    public ExcelListener(EduSubjectService service) {
        this.service = service;
        System.out.println(service);
    }

    public void setService(EduSubjectService service) {
        this.service = service;
    }

    @Override
    public void invoke(subjectData data, AnalysisContext context) {
        if(data==null){
            throw  new GuilException(20001,"excel表中的数据为空!");
        }
        //一行一行读取，每次读取2个值，第一个一级分类第二个二级分类


        //1级分类不能重复

        EduSubject one = this.exitOneSubject(data.getOneSubjectName());
        if(one==null){
            one  = new EduSubject();
            one.setParentId("0");
            one.setTitle(data.oneSubjectName);
            service.save(one);
        }
        //2级分类不能重复
        //获取1级分类的id值
        String pid=one.getId();
        System.out.println(one.toString());
        EduSubject two = this.exitTwoSubject(data.getTwoSubjectName(), pid);
        if(two==null){
            two=new EduSubject();
            two.setTitle(data.twoSubjectName);
            two.setParentId(pid);
            service.save(two);
            System.out.println(two);
        }

    }

    /**
     * 1级分类重复判断
     * @param name
     * @return
     */
    public EduSubject exitOneSubject(String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        //因为1级分类的父id是0
        wrapper.eq("parent_id","0");
        return service.getOne(wrapper);

    }

    /**
     * 2级分类重复判断
     * @param name
     * @return
     */

    public EduSubject exitTwoSubject(String name,String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        //二级分类的爹
        wrapper.eq("parent_id",pid);
        return service.getOne(wrapper);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
